home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_01_05 / 1n05020a < prev    next >
Text File  |  1990-03-25  |  2KB  |  72 lines

  1. /* Listing 3
  2.  
  3.    findtext.c: Locate places in file with a pattern
  4.  
  5.    Written by Hugh Staley
  6.               Box 842
  7.               Los Alamos, NM 87544
  8.  */
  9.  
  10. #include <stdio.h>
  11.  
  12. char Match [100] = {"FILE BLOCK"};
  13.  
  14. void Search (fd)
  15.     FILE *fd;
  16.  
  17.     {
  18.     int Count = 0, Ch, Length;
  19.     long Offset;
  20.  
  21.     Length = strlen (Match);
  22.     while ((Ch = getc (fd)) != EOF)
  23.         if (Count < Length)
  24.             if (Ch == Match [Count])
  25.                 {
  26.                 ++Count;
  27.                 if (Count == 1)
  28.                     Offset = ftell (fd) - 1;
  29.                 else if (Count == Length)
  30.                     printf ("%lX: %s", Offset, Match);
  31.                 }
  32.             else
  33.                 Count = 0;
  34.         else
  35.             if (Ch == '\0')
  36.                 {
  37.                 printf (": %d bytes\n", ++Count);
  38.                 Count = 0;
  39.                 }
  40.             else
  41.                 {
  42.                 ++Count;
  43.                 printf ("%c", Ch);
  44.                 }
  45.     }   /* Search file */
  46.  
  47. main (argc, argv)
  48. int argc;
  49. char *argv [];
  50.     
  51.     {
  52.     FILE *fd;
  53.  
  54.     if (argc < 2 || argc > 3)
  55.         {
  56.         printf ("usage: findtext  [-tTEXT]  fn\n");
  57.         exit (0);
  58.         }
  59.   
  60.     if (strncmp (argv [1], "-t", 2) == 0)
  61.         strcpy (Match, argv [1] + 2);
  62.     
  63.     if ((fd = fopen (argv [argc - 1], "rb")) != NULL)
  64.         {
  65.         Search (fd);
  66.         fclose (fd);
  67.         }
  68.     else
  69.         printf ("Cannot open \"%s\".\n", argv [argc - 1]);
  70.     }
  71.  
  72.